package com.bms.admin.base.role.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bms.admin.base.role.entity.Role;
import com.bms.admin.base.role.entity.RoleMenu;
import com.bms.admin.base.role.mapper.RoleMapper;
import com.bms.admin.base.role.service.IRoleMenuService;
import com.bms.admin.base.role.service.IRoleService;
import com.bms.admin.base.role.vo.RoleVo;
import com.bms.auth.SubjectUtil;
import com.feilong.core.bean.ConvertUtil;
import com.feilong.core.util.CollectionsUtil;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author xj
 * @since 2018-08-09
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

	@Autowired
	private IRoleMenuService roleMenuService;
	@Autowired
	private RoleMapper roleMapper;
	
	@Override
	public void savePermission(Long roleId, List<Long> menuIds) {
		List<RoleMenu> roleResources = roleMenuService.selectByMap(ConvertUtil.toMap("role_id",(Object)roleId));
		List<RoleMenu> newMenus = new ArrayList<>();
		for(Long menuId : menuIds){
			RoleMenu rm = new RoleMenu(roleId,menuId);
			newMenus.add(rm);
		}

		//查找出需要删除的
		List<RoleMenu> removeMenus = CollectionsUtil.selectRejected(roleResources,IRoleService.MENU_ID,menuIds);
		//查找需要新增的
		List<RoleMenu> addMenus = CollectionsUtil.selectRejected(newMenus,IRoleService.MENU_ID,CollectionsUtil.getPropertyValueList(roleResources, IRoleService.MENU_ID));
		for(RoleMenu r:removeMenus){
			roleMenuService.deleteById(r.getId());
		}
		for(RoleMenu r:addMenus){
			roleMenuService.insert(r);
		}
		SubjectUtil.getInstance().updateCachePermission();
	}

	@Override
	public Page<RoleVo> selectRoleList(Page<RoleVo> page, Wrapper<RoleVo> ew) {
		return page.setRecords(roleMapper.selectRoleList(page, ew));
	}

}
